const handleBlogRouter = require('./src/router/blog')
const handleUserRouter = require('./src/router/user')
const {get ,set }=require('./src/db/redis')
const querystring = require('querystring')
const SESSION_DATA={}
const getPostData = (req) => {
    const promise = new Promise((resolve, reject) => {
        if (req.method !== 'POST') {
            resolve({})
            return
        }
       
        if (req.headers['content-type'] !== 'application/json') {
            resolve({})
            return
        }
        
        let postData = ''
        req.on('data', chunk => {
            postData += chunk.toString()
        })
        req.on('end', () => {
            if (!postData) {
                resolve({})
                return
            }
            resolve(
                JSON.parse(postData)
            )
        })
    })
    return promise
}
const serverHandel = (req, res) => {
    //设置返回格式 json
    res.setHeader('Content-type', 'application/json')
    //url地址
    const url = req.url
    req.path = url.split('?')[0]
    //解析query
    req.query = querystring.parse(url.split('?')[1])
    //解析cookie 
    req.cookie={}
    const cookiestring=req.headers.cookie || ""
    cookiestring.split(';').forEach(item=>{
        if(!item){
            return
        }
        const arr=item.split('=')
        const key = arr[0].trim()
        const val =arr[1].trim()
        req.cookie[key]=val

    })
    //解析session
    const userId=req.cookie.userid
    if(userId){
        if(SESSION_DATA[req.cookie]){
            req.session=SESSION_DATA[userId]
        }
    }
    
    getPostData(req).then(postData => {
        req.body = postData
        //处理blog路由
        const blogResult =handleBlogRouter(req, res)
        if(blogResult){
            blogResult.then(blogData=>{
                res.end(
                    JSON.stringify(blogData)
                )
            })
            return
        }
        
        // const blogData = handleBlogRouter(req, res)
        // if (blogData) {
        //     res.end(
        //         JSON.stringify(blogData)
        //     )
        //     return
        // }
        //这里处理user路由
        const userResult=handleUserRouter(req,res)
        if(userResult){
            userResult.then(userdata=>{
                res.end(
                    JSON.stringify(userdata)
                )
            })
            return
        }
        // const userData = handleUserRouter(req, res)
        // if (userData) {
        //     res.end(
        //         JSON.stringify(userData)
        //     )
        //     return
        // }
        //没有路由
        res.writeHead(404, {
            "Content-type": "text/plain"
        })
        res.write("404 Not Found\n")
        res.end()
    })



}
module.exports = serverHandel


//process.env.NODE_ENV
//这是运行在什么环境里面的 比如说这个事dev的开发环境上
//process是node提供的一个全局变量